package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysRegion;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.mapper.SysRegionMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.modules.system.model.SysRegionTreeModel;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysRegionService;
import org.jeecg.modules.system.util.FindsDepartsChildrenUtil;
import org.jeecg.modules.system.util.FindsRegionsChildrenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysRegionServiceImpl extends ServiceImpl<SysRegionMapper, SysRegion> implements ISysRegionService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public List<SysRegion> queryTreeListNoPage(QueryWrapper<SysRegion> queryWrapper) {
        List<SysRegion> dataList = baseMapper.selectList(queryWrapper);
        List<SysRegion> mapList = new ArrayList<>();
        for(SysRegion data : dataList){
            String pidVal = data.getPid();
            //递归查询子节点的根节点
            if(pidVal != null && !ISysRegionService.NOCHILD.equals(pidVal)){
                SysRegion rootVal = this.getTreeRoot(pidVal);
                if(rootVal != null && !mapList.contains(rootVal)){
                    mapList.add(rootVal);
                }
            }else{
                if(!mapList.contains(data)){
                    mapList.add(data);
                }
            }
        }
        return mapList;
    }
    /**
     * queryTreeList 对应 queryTreeList 查询所有的部门数据,以树结构形式响应给前端
     */
    @Override
//    @Cacheable(value = CacheConstant.SYS_REGIONS_CACHE)
    public List<SysRegionTreeModel> queryTreeList() {
        LambdaQueryWrapper<SysRegion> query = new LambdaQueryWrapper<SysRegion>();
        query.eq(SysRegion::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
        query.le(SysRegion::getPid, 1);
        query.orderByAsc(SysRegion::getSort);
        List<SysRegion> list = this.list(query);
        //update-begin---author:wangshuai ---date:20220307  for：[JTC-119]在部门管理菜单下设置部门负责人 创建用户的时候不需要处理
        //设置用户id,让前台显示
        this.setUserIdsByRegionList(list);
        //update-begin---author:wangshuai ---date:20220307  for：[JTC-119]在部门管理菜单下设置部门负责人 创建用户的时候不需要处理
        // 调用wrapTreeDataToTreeList方法生成树状数据
        List<SysRegionTreeModel> listResult = FindsRegionsChildrenUtil.wrapTreeDataToTreeList(list);
        return listResult;
    }

    /**
     * queryTreeList 根据部门id查询,前端回显调用
     */
    @Override
    public List<SysRegionTreeModel> queryTreeList(String ids) {
        List<SysRegionTreeModel> listResult=new ArrayList<>();
        LambdaQueryWrapper<SysRegion> query = new LambdaQueryWrapper<SysRegion>();
        query.eq(SysRegion::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
        if(oConvertUtils.isNotEmpty(ids)){
            query.in(true,SysRegion::getPid,ids.split(","));
        }
        query.orderByAsc(SysRegion::getSort);
        List<SysRegion> list= this.list(query);
        for (SysRegion region : list) {
            listResult.add(new SysRegionTreeModel(region));
        }
        return  listResult;

    }
    @Override
    public List<SelectTreeModel> queryListByCode(String parentCode) {
        String pid = ROOT_PID_VALUE;
        if (oConvertUtils.isNotEmpty(parentCode)) {
            LambdaQueryWrapper<SysRegion> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysRegion::getPid, parentCode);
            List<SysRegion> list = baseMapper.selectList(queryWrapper);
            if (list == null || list.size() == 0) {
                throw new JeecgBootException("该编码【" + parentCode + "】不存在，请核实!");
            }
            if (list.size() > 1) {
                throw new JeecgBootException("该编码【" + parentCode + "】存在多个，请核实!");
            }
            pid = list.get(0).getId();
        }
        return baseMapper.queryListByPid(pid, null);
    }
    @Override
    public List<SelectTreeModel> queryListByPid(String pid) {
        if (oConvertUtils.isEmpty(pid)) {
            pid = ROOT_PID_VALUE;
        }
        return baseMapper.queryListByPid(pid, null);
    }
    /**
     * 通过部门集合为部门设置用户id，用于前台展示
     * @param regionList 部门集合
     */
    private void setUserIdsByRegionList(List<SysRegion> regionList) {
        //查询负责部门不为空的情况
        LambdaQueryWrapper<SysUser> query  = new LambdaQueryWrapper<>();
        query.isNotNull(SysUser::getRegionIds);
        List<SysUser> users = sysUserMapper.selectList(query);
        Map<String,Object> map = new HashMap(5);
        //先循环一遍找到不同的负责部门id
        for (SysUser user:users) {
            String regionIds = user.getRegionIds();
            String[] regionIdArray = regionIds.split(",");
            for (String regionId:regionIdArray) {
                //mao中包含部门key，负责用户直接拼接
                if(map.containsKey(regionId)){
                    String userIds = map.get(regionId) + "," + user.getId();
                    map.put(regionId,userIds);
                }else{
                    map.put(regionId,user.getId());
                }
            }
        }
        //循环部门集合找到部门id对应的负责用户
        for (SysRegion sysRegion:regionList) {
            if(map.containsKey(sysRegion.getId())){
                sysRegion.setDirectorUserIds(map.get(sysRegion.getId()).toString());
            }
        }
    }
    /**
     * 递归查询节点的根节点
     * @param pidVal
     * @return
     */
    private SysRegion getTreeRoot(String pidVal){
        SysRegion data =  baseMapper.selectById(pidVal);
        if(data != null && !ISysRegionService.ROOT_PID_VALUE.equals(data.getPid())){
            return this.getTreeRoot(data.getPid());
        }else{
            return data;
        }
    }
}
